package com.mu.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mu.common.Constants;
import com.mu.controller.dto.PasswordDTO;
import com.mu.controller.dto.UserDTO;
import com.mu.entity.Record;
import com.mu.entity.User;
import com.mu.common.Result;
import com.mu.exception.ServiceException;
import com.mu.service.impl.UserServiceImpl;
import com.mu.token.JwtToken;
import com.mu.utils.JwtUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.mu.service.UserService;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author mu
 * @since 2022-10-21
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private UserServiceImpl userServiceImpl;

    private User user;//根据account查询的当前用户信息

    @RequiresRoles(value = "管理员")
    @PostMapping
    public Result save(@RequestBody User user) {
        return Result.success(userService.saveOrUpdate(user));
    }

    @RequiresRoles(value = "管理员")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(userService.removeById(id));
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids){
        return Result.success(userService.removeByIds(ids));
    }

    @RequiresRoles(value = "管理员")
    @GetMapping
    public Result findAll() {
        return Result.success(userService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(userService.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
    @RequestParam Integer pageSize) {
        return Result.success(userService.page(new Page<>(pageNum, pageSize)));
    }

    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO) {
        return userService.login(userDTO);
    }

    /**
     * 传入excel表格导入并更新数据
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws IOException {

        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
        //List<Record> list = reader.readAll(Record.class);

        // 方式2：忽略表头的中文，直接读取表的内容
        List<List<Object>> list = reader.read(1);
        List<User> users  = CollUtil.newArrayList();
        for (List<Object> row : list) {
            User user = new User();
            user.setAccount(row.get(0).toString());
            user.setPassword(row.get(1).toString());
            user.setName(row.get(2).toString());
            user.setRole(row.get(3).toString());
            user.setPhone(row.get(4).toString());
            users.add(user);
        }
        for (User res : users) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("account", res.getAccount());
            User findOne  = userService.getOne(queryWrapper);
            if (findOne != null) {
                userService.update(res,queryWrapper);
            } else {
                userService.save(res);
            }
        }
        return Result.success(true);
    }

    /**
     *用户自己修改密码的接口
     * @param passwordDTO
     * @return
     */
    @PostMapping("reset")
    public Result realReset(@RequestBody PasswordDTO passwordDTO) {
        if (StrUtil.isBlank(passwordDTO.getAccount()) || StrUtil.isBlank(passwordDTO.getUsername())) {
            throw new ServiceException(Constants.CODE_400,"参数错误");
        }
        //查询与数据库中的学号和姓名是否一致
        QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("account", passwordDTO.getAccount());
        queryWrapper1.eq("name", passwordDTO.getUsername());
        User user = userService.getOne(queryWrapper1);
        if (user == null) {
            throw new ServiceException("-1","信息错误");
        }
        if ("".equals(passwordDTO.getPassword1()) || "".equals(passwordDTO.getPassword2())) {
            throw new ServiceException(Constants.CODE_400,"参数错误,请重新输入");
        }
        else if (user == null) {
            throw new ServiceException(Constants.CODE_400,"请先输入姓名学号验证");
        }
        else if (!passwordDTO.getPassword1().equals(passwordDTO.getPassword2())) {
            throw new ServiceException(Constants.CODE_400,"两次密码不一致，请重新输入");
        }
        else if (passwordDTO.getPassword1().equals(passwordDTO.getPassword2())) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("account", user.getAccount());
            user.setPassword(passwordDTO.getPassword1());
            userService.update(user,queryWrapper);
        }
        return new Result(Constants.CODE_200,"修改成功，请重新登录",null);
    }

    /**
     * 管理员重置密码的接口 重置为学号
     * @param passwordDTO
     * @return
     */
    @RequiresRoles(value = "管理员")
    @PostMapping("adminReset")
    public Result adminReset(@RequestBody PasswordDTO passwordDTO) {
        if (StrUtil.isBlank(passwordDTO.getAccount()) || StrUtil.isBlank(passwordDTO.getUsername())) {
            throw new ServiceException(Constants.CODE_400,"参数错误");
        }
        //查询与数据库中的学号和姓名是否一致
        QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("account", passwordDTO.getAccount());
        queryWrapper1.eq("name", passwordDTO.getUsername());
        User user = userService.getOne(queryWrapper1);
        if (user == null) {
            throw new ServiceException("-1","信息错误");
        } else {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("account", user.getAccount());
            user.setPassword(user.getAccount());
            userService.update(user,queryWrapper);
        }
        return new Result(Constants.CODE_200,"修改成功，请重新登录",null);
    }

}

